<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.transportId ? $t('crud.addTitle') : $t('temp.modify')"
    :close-on-click-modal="false"
    width="75%"
    top="3vh"
    class="dialog-transport-add-or-update"
    @close="close"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :label-width="$t('language') === 'English' ? '190px' : '130px'"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('transport.name')"
        prop="transName"
        maxlength="36"
        show-word-limit
        :rules="[{ required: true, message: $t('shop.templateNameCannotBeEmpty') }]"
      >
        <el-input
          v-model="dataForm.transName"
          :placeholder="$t('transport.name')"
          maxlength="36"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('transport.chargePrice')"
        prop="chargeType"
      >
        <el-radio-group
          v-model="dataForm.chargeType"
          :disabled="dataForm.isFreeFee === 1"
          @change="onChangeChargeType"
        >
          <el-radio :label="0">
            {{ $t('transport.byCount') }}
          </el-radio>
          <el-radio :label="1">
            {{ $t('transport.byWeight') }}
          </el-radio>
          <el-radio :label="2">
            {{ $t('transport.byVolume') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 添加可配送的区域和邮费 START -->
      <el-table
        :data="dataForm.transfees"
        border
        style="width: 100%"
      >
        <el-table-column
          header-align="center"
          align="center"
          :label="$t('transport.distributableArea')"
        >
          <template #default="scope">
            <span v-if="scope.$index === 0 && dataForm.isFreeFee === 1">{{
              $t('transport.allRegions')
            }}</span>
            <template v-if="dataForm.isFreeFee === 0">
              <span
                v-if="!scope.row.addrNameList || !scope.row.addrNameList.length"
                class="city-name"
              >{{ $t('shop.pleaseSelectADeliveryArea') }}</span>
              <span>
                <!-- {{scope.row.addrNameList.toString()}} -->
                <span
                  v-for="(city, index) in scope.row.addrNameList"
                  :key="index"
                  class="city-name"
                >{{ city }}</span>
              </span>
              <div
                class="default-btn text-btn"
                @click="onAddOrUpdate(`${scope.$index}`)"
              >
                {{ $t('groups.edit') }}
              </div>
              <div
                v-if="scope.$index > 0"
                class="default-btn text-btn"
                @click="onDelete(`${scope.$index}`)"
              >
                {{ $t('text.delBtn') }}
              </div>
            </template>
          </template>
        </el-table-column>
        <!-- 首件数量 -->
        <el-table-column
          header-align="center"
          align="center"
          :label="tableTitle[0]"
        >
          <template #default="scope">
            <el-form-item
              :prop="`transfees.${scope.$index}.firstPiece`"
              label-width="0px"
              class="errorTips"
              style="margin-bottom: 0 !important"
              :rules="[{ required: true, message: `${tableTitle[0]}${$t('publics.noNull')}` }]"
            >
              <el-input
                v-model="scope.row.firstPiece"
                type="number"
                oninput="if(value.length>10)value=value.slice(0,10)"
                :disabled="!scope.row.status && scope.$index === 0"
                :min="1"
                :max="1000000000"
                @change="onCheckChargeType(scope.row, 'firstPiece', dataForm.chargeType)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 首件邮费 -->
        <el-table-column
          header-align="center"
          align="center"
          :label="tableTitle[1]"
        >
          <template #default="scope">
            <el-form-item
              :prop="`transfees.${scope.$index}.firstFee`"
              label-width="0px"
              class="errorTips"
              style="margin-bottom: 0 !important"
              :rules="[{ required: true, message: `${tableTitle[1]}${$t('publics.noNull')}` }]"
            >
              <el-input-number
                v-model="scope.row.firstFee"
                style="width: 80%"
                :disabled="!scope.row.status && scope.$index === 0"
                :precision="2"
                :min="0"
                :max="1000000000"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 续件数量 -->
        <el-table-column
          header-align="center"
          align="center"
          :label="tableTitle[2]"
        >
          <template #default="scope">
            <el-form-item
              :prop="`transfees.${scope.$index}.continuousPiece`"
              label-width="0px"
              class="errorTips"
              style="margin-bottom: 0 !important"
              :rules="[{ required: true, message: `${tableTitle[2]}${$t('publics.noNull')}` }]"
            >
              <el-input
                v-model="scope.row.continuousPiece"
                type="number"
                oninput="if(value.length>10)value=value.slice(0,10)"
                :disabled="!scope.row.status && scope.$index === 0"
                @change="onCheckChargeType(scope.row, 'continuousPiece', dataForm.chargeType)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 续件邮费 -->
        <el-table-column
          header-align="center"
          align="center"
          :label="tableTitle[3]"
        >
          <template #default="scope">
            <el-form-item
              :prop="`transfees.${scope.$index}.continuousFee`"
              label-width="0px"
              class="errorTips"
              style="margin-bottom: 0 !important"
              :rules="[{ required: true, message: `${tableTitle[3]}${$t('publics.noNull')}` }]"
            >
              <el-input-number
                v-model="scope.row.continuousFee"
                style="width: 80%"
                :disabled="!scope.row.status && scope.$index === 0"
                :precision="2"
                :min="0"
                :max="1000000000"
              />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>

      <div
        v-if="dataForm.isFreeFee === 0"
        style="margin-top: 20px"
      >
        <div
          class="default-btn icon-btn"
          @click="addTransfee()"
        >
          {{ $t('shop.addAreaAndShipping') }}
        </div>
      </div>
      <!-- 添加可配送的区域和邮费 END -->
      <!-- 指定条件包邮 START -->
      <el-checkbox
        v-if="!dataForm.isFreeFee"
        v-model="dataForm.hasFreeCondition"
        style="margin-top: 10px; font-size: 50px"
      >
        {{ $t('shop.freeShippingOnSpecifiedConditions') }}
      </el-checkbox>
      <el-table
        v-if="dataForm.hasFreeCondition && !dataForm.isFreeFee"
        :data="dataForm.transfeeFrees"
        border
        style="width: 100%"
      >
        <el-table-column
          header-align="center"
          align="center"
          :label="$t('transport.selArea')"
        >
          <template #default="scope">
            <span
              v-if="!scope.row.freeAddrNameList || !scope.row.freeAddrNameList.length"
              class="city-name"
            >{{ $t('transport.selCity') }}</span>
            <span
              v-for="(city, index) in scope.row.freeAddrNameList"
              :key="index"
              class="city-name"
            >{{ city }}</span>
            <div
              v-if="isAuth('shop:transfee:update')"
              class="default-btn text-btn"
              @click="addOrUpdateTransfeeFree(`${scope.$index}`)"
            >
              {{ $t('groups.edit') }}
            </div>
            <div
              v-if="isAuth('shop:transfee:delete') && scope.$index > 0"
              class="default-btn text-btn"
              @click="deleteTransfeeFree(`${scope.$index}`)"
            >
              {{ $t('text.delBtn') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          :label="$t('transport.setShopPrice')"
        >
          <template #default="scope">
            <el-radio-group v-model="scope.row.freeType">
              <el-radio :label="0">
                {{
                  [$t('transport.byCount'), $t('transport.byWeight'), $t('transport.byVolume')][
                    dataForm.chargeType
                  ]
                }}
              </el-radio>
              <el-radio :label="1">
                {{ $t('product.freeShiullAmount') }}
              </el-radio>
              <el-radio :label="2">
                {{
                  [
                    $t('transport.fullCount'),
                    $t('transport.fullWeight'),
                    $t('transport.fullVolume')
                  ][dataForm.chargeType]
                }}{{ $t('transport.fullAmount1') }}{{ $t('transport.shippingIncluded') }}
              </el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="left"
        >
          <template #default="scope">
            <!-- 满xx元包邮 -->
            <el-form-item
              v-if="scope.row.freeType === 1 || scope.row.freeType === 2"
              :prop="`transfeeFrees.${scope.$index}.amount`"
              label-width="0px"
              :rules="[{ required: true, message: `${$t('publics.noNull')}` }]"
              style="margin-bottom: 10px !important; margin-top: 10px !important"
            >
              <el-input
                v-model="scope.row.amount"
                type="number"
                oninput="if(value.length>10)value=value.slice(0,10)"
                :precision="2"
                @change="convertPrice(scope.row, 'amount')"
              >
                <template #prepend>
                  {{ $t('marketing.full') }}
                </template>
                <template #append>
                  {{ $t('admin.dollar') }}{{ $t('product.freeShipping') }}
                </template>
              </el-input>
            </el-form-item>
            <!-- 满xx件/重量/体积包邮 -->
            <el-form-item
              v-if="scope.row.freeType === 0 || scope.row.freeType === 2"
              :prop="`transfeeFrees.${scope.$index}.piece`"
              label-width="0px"
              :rules="[{ required: true, message: `${$t('publics.noNull')}` }]"
              style="margin-bottom: 10px !important; margin-top: 10px !important"
            >
              <el-input
                v-model="scope.row.piece"
                type="number"
                oninput="if(value.length>10)value=value.slice(0,10)"
                @change="onCheckChargeType(scope.row, 'piece', dataForm.chargeType)"
              >
                <template #prepend>
                  {{ $t('marketing.full') }}
                </template>
                <template #append>
                  {{
                    [$t('transport.pieces'), 'kg', 'm³'][dataForm.chargeType]
                  }}
                </template>
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <div
        v-if="dataForm.isFreeFee === 0"
        style="margin-top: 20px"
      >
        <div
          class="default-btn icon-btn"
          :class="{ 'disabled-btn': !dataForm.hasFreeCondition }"
          @click="addTransfeeFree()"
        >
          {{ $t('shop.clickToAddTheSpecifiedShippingConditions') }}
        </div>
      </div>
      <!-- 指定条件包邮 END -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="close"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="onGetDataList"
    />
  </el-dialog>
</template>

<script setup>
import { areaNameList } from '@/utils/addr'
import { ElMessage } from 'element-plus'
import { isAuth } from '@/utils'
import AddOrUpdate from './city-add-or-update.vue'

const emit = defineEmits(['refreshDataList', 'close'])

const addOrUpdateVisible = ref(false)
const visible = ref(false)
watch(visible, newVal => {
  // 如果当前对话框不可见，则关闭选择城市的对话框
  if (!newVal) {
    addOrUpdateVisible.value = false
  }
})
const dataForm = ref({
  hasFreeCondition: false,
  transName: '',
  createTime: '',
  chargeType: 0,
  transportId: 0,
  isFreeFee: 0,
  transfees: [{ cityList: [], status: 1 }],
  transfeeFrees: [{ freeCityList: [], freeType: 0 }]
})
const tableTitle = computed(() => {
  const titles = [
    [
      $t('transport.firstPiece'),
      $t('transport.transportationCost'),
      $t('transport.continuationPiece'),
      $t('transport.continuationCost')
    ],
    [
      $t('transport.firstWeight'),
      $t('transport.transportationCost'),
      $t('transport.continuedWeight'),
      $t('transport.continuationCost')
    ],
    [
      $t('transport.firstVolume'),
      $t('transport.transportationCost'),
      $t('transport.continuedVolume'),
      $t('transport.continuationCost')
    ]
  ]
  if (dataForm.value.chargeType) {
    return titles[dataForm.value.chargeType]
  }
  return titles[0]
})
const isSubmit = ref(false)
const transfeesBin = ref([]) // 可配送区域运费，禁止选中列表
const transfeeFreesBin = ref([]) // 指定条件包邮，禁止选中列表

const init = id => {
  visible.value = true
  isSubmit.value = false
  dataForm.value.transportId = id || 0
  nextTick(() => {
    dataFormRef.value?.resetFields()
    dataForm.value = {
      hasFreeCondition: false,
      transName: '',
      createTime: '',
      chargeType: 0,
      transportId: 0,
      isFreeFee: 0,
      transfees: [{ cityList: [], addrNameList: [], status: 1 }],
      transfeeFrees: [{ freeCityList: [], freeType: 0 }]
    }
  })

  // 重置买家承担运费时的数据
  transfeesBin.value = []
  transfeeFreesBin.value = []
  onGetTransport()
}
const onGetTransport = () => {
  if (dataForm.value.transportId) {
    http({
      // 获取运费模板数据
      url: http.adornUrl(`/shop/transport/info/${dataForm.value.transportId}`),
      method: 'get'
    }).then(({ data }) => {
      onGetAreaListInfo()
      if (data.isFreeFee) {
        data.transfees[0].status = 0
      } else {
        data.transfees[0].status = 1
      }
      dataForm.value = data
      if (!dataForm.value.transfeeFrees.length) {
        dataForm.value.transfeeFrees = [{ freeCityList: [], freeType: 0 }]
      }
      dataForm.value.hasFreeCondition = !!data.hasFreeCondition
      onHandleBinAreas()
    })
  } else {
    onGetAreaListInfo()
    onHandleBinAreas()
  }
}
const onGetDataList = (row, cityList, type) => {
  if (type === 0) {
    dataForm.value.transfees[row].cityList = cityList
    dataForm.value.transfees[row].addrNameList = onSetAddrInfoByAreaList(cityList)
  }
  if (type === 1) {
    dataForm.value.transfeeFrees[row].freeCityList = cityList
    dataForm.value.transfeeFrees[row].freeAddrNameList = onSetAddrInfoByAreaList(cityList)
  }
  onHandleBinAreas()
}
/**
 * 获取省市区信息
 */
const areaList = ref([])
const areaListDB = ref([])
const onGetAreaListInfo = () => {
  http({
    url: http.adornUrl('/admin/area/areaListInfo'),
    method: 'get'
  }).then(({ data }) => {
    areaListDB.value = data
    areaList.value = JSON.parse(JSON.stringify(data))
    if (dataForm.value.transfees.length > 0) {
      onGetAreaListByType(0)
    }
    if (dataForm.value.transfeeFrees.length > 0) {
      onGetAreaListByType(1)
    }
  })
}
const onGetAreaListByType = type => {
  if (type === 0) {
    for (let t = 0; t < dataForm.value.transfees.length; t++) {
      dataForm.value.transfees[t].addrNameList = onSetAddrInfoByAreaList(dataForm.value.transfees[t].cityList)
    }
  }
  if (type === 1) {
    for (let f = 0; f < dataForm.value.transfeeFrees.length; f++) {
      dataForm.value.transfeeFrees[f].freeAddrNameList = onSetAddrInfoByAreaList(dataForm.value.transfeeFrees[f].freeCityList)
    }
  }
}
// 收费方式切换
const onChangeChargeType = type => {
  dataForm.value.transfees.forEach(item => {
    item.firstPiece && onCheckChargeType(item, 'firstPiece', type)
    item.continuousPiece && onCheckChargeType(item, 'continuousPiece', type)
  })
  dataForm.value.transfeeFrees.forEach(item => {
    item.piece && onCheckChargeType(item, 'piece', type)
  })
}
// 价格格式化
const convertPrice = (row, attr) => {
  const price = +onCheckAmount(row[attr])
  row[attr] = price.toFixed(2)
}
// 根据收费方式格式化输入的值
const onCheckChargeType = (row, attr, chargeType) => {
  // 0：按件数  1：按重量  2：按体积
  if (chargeType === 0) {
    const number = onGetNumber(row[attr])
    row[attr] = number > 0 ? number : 1
  } else if (chargeType === 1 || chargeType === 2) {
    const price = +onCheckAmount(row[attr])
    row[attr] = price.toFixed(2)
  }
}
const onGetNumber = num => {
  num = Math.round(num)
  return num < 0 ? 0 : num
}
const onCheckAmount = data => {
  const reg = /^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/
  let num = data
  if (!reg.test(data)) {
    num = Math.round(data * 100) / 100
  }
  if (num < 0) {
    num = 1
  }
  return num
}
/**
 * 将运费模板中的地址存入地址列表中
 */
const onSetAddrInfoByAreaList = cityList => {
  return areaNameList(JSON.parse(JSON.stringify(areaListDB.value)), cityList)
}
// 添加运费项
const editVisible = ref(false)
const addTransfee = () => {
  editVisible.value = true
  dataForm.value.transfees.push({ cityList: [], status: 1 })
}
// 删除运费项
const onDelete = rowIndex => {
  dataForm.value.transfees.splice(rowIndex, 1)
  onHandleBinAreas()
}
// 可配送区域和运费编辑
const addOrUpdateRef = ref(null)
const onAddOrUpdate = rowIndex => {
  addOrUpdateVisible.value = true
  let allSelectCityList = []
  for (let i = 1; i < dataForm.value.transfees.length; i++) {
    const cityList = dataForm.value.transfees[i]?.cityList
    allSelectCityList = allSelectCityList.concat(cityList)
  }
  nextTick(() => {
    addOrUpdateRef.value?.init(
      rowIndex,
      dataForm.value.transfees[rowIndex].cityList || [],
      allSelectCityList,
      0,
      transfeesBin.value
    )
  })
}
// 添加指定包邮条件
const addTransfeeFree = () => {
  if (!dataForm.value.hasFreeCondition) {
    return
  }
  dataForm.value.transfeeFrees.push({ freeCityList: [], freeType: 0 })
}
// 删除指定包邮条件
const deleteTransfeeFree = rowIndex => {
  dataForm.value.transfeeFrees.splice(rowIndex, 1)
  onHandleBinAreas()
}
// 指定包邮条件编辑
const addOrUpdateTransfeeFree = rowIndex => {
  addOrUpdateVisible.value = true
  let allSelectCityList = []
  for (let i = 1; i < dataForm.value.transfeeFrees.length; i++) {
    const freeCityList = dataForm.value.transfeeFrees[i].freeCityList
    allSelectCityList = allSelectCityList.concat(freeCityList)
  }
  nextTick(() => {
    addOrUpdateRef.value?.init(
      rowIndex,
      dataForm.value.transfeeFrees[rowIndex].freeCityList || [],
      allSelectCityList,
      1,
      transfeeFreesBin.value
    )
  })
}

// 设置不可选中
const onHandleBinAreas = () => {
  transfeesBin.value = []
  transfeeFreesBin.value = []
  const transfees = dataForm.value.transfees
  const transfeeFrees = dataForm.value.transfeeFrees
  if (transfees.length > 0) {
    transfees.forEach(i => {
      if (i.cityList.length > 0) {
        i.cityList.forEach(j => {
          if (!judgeArrHaving(transfeesBin.value, j)) {
            transfeesBin.value.push(j.areaId)
          }
        })
      }
    })
  }
  if (transfeeFrees.length > 0) {
    transfeeFrees.forEach(i => {
      if (i.freeCityList.length > 0) {
        i.freeCityList.forEach(j => {
          if (!judgeArrHaving(transfeeFreesBin.value, j)) {
            transfeeFreesBin.value.push(j.areaId)
          }
        })
      }
    })
  }
}
const judgeArrHaving = (arr, data) => {
  let isExist = false
  if (arr.length < 1) {
    return isExist
  }
  if (arr.includes(data.areaId)) {
    isExist = true
  }
  return isExist
}
const emptyCityHint = () => {
  ElMessage({
    message: $t('shop.pleaseSelectADeliveryArea'),
    type: 'error',
    duration: 1500
  })
}
const formWriteHint = () => {
  ElMessage({
    message: $t('shop.pleaseWriteInfo'),
    type: 'error',
    duration: 1500
  })
}
// 表单提交
const dataFormRef = ref(null)
const hasFreeCondition = ref(0)
const onSubmit = () => {
  dataFormRef.value.validate(valid => {
    if (!valid) {
      formWriteHint()
    }
    if (valid) {
      const transFeesLen = dataForm.value.transfees.length || 0
      if (!transFeesLen) {
        emptyCityHint()
        return
      }
      for (let i = 0; i < transFeesLen; i++) {
        const transfee = dataForm.value.transfees[i]
        if (transfee.cityList.length === 0 && dataForm.value.isFreeFee === 0) {
          emptyCityHint()
          return
        }
      }
      if (
        dataForm.value.hasFreeCondition &&
        (!dataForm.value.transfeeFrees || dataForm.value.transfeeFrees.length === 0)
      ) {
        ElMessage({
          message: $t('shop.setRegionalConditions'),
          type: 'error',
          duration: 1500
        })
        return
      }
      if (dataForm.value.hasFreeCondition) {
        hasFreeCondition.value = 1
      } else {
        hasFreeCondition.value = 0
      }
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      http({
        url: http.adornUrl('/shop/transport'),
        method: dataForm.value.transportId ? 'put' : 'post',
        data: http.adornData({
          transportId: dataForm.value.transportId || undefined,
          transName: dataForm.value.transName,
          chargeType: dataForm.value.chargeType,
          isFreeFee: dataForm.value.isFreeFee,
          transfees: dataForm.value.transfees,
          transfeeFrees: dataForm.value.transfeeFrees,
          hasFreeCondition: hasFreeCondition.value
        })
      })
        .then(() => {
          ElMessage({
            message: $t('publics.operation'),
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false
              emit('refreshDataList', dataForm.value.transName)
              close()
            }
          })
        })
        .catch(() => {
          isSubmit.value = false
        })
    }
  })
}
const close = () => {
  emit('close', 'close')
}
defineExpose({ init })
</script>

<style lang="scss" scoped>
.dialog-transport-add-or-update {
  :deep(.el-table.el-table--fit.el-table--enable-row-transition .el-form-item) {
    margin-bottom: 30px !important;
  }

  div :deep(.is-success .el-input-number__increase) {
    right: 0 !important;
  }
  div :deep(.el-input-number__increase) {
    border-left: 1px solid #dcdfe6 !important;
  }
  .errorTips div :deep(.el-form-item__error) {
    position: static !important;
  }
  div :deep(.el-form-item__error) {
    position: static !important;
  }

  div :deep(.el-radio__label) {
    text-overflow: ellipsis;
    white-space: normal;
    line-height: 18px;
    vertical-align: middle;
    display: inline-block;
    text-align: left;
  }

  .city-name {
    margin: 4px;
  }
}
</style>
